import os

from flask import Flask
from flask_cors import CORS
from nacos import NacosClient

from .extensions import db


def create_app(config_name=None):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(
        SECRET_KEY='dev',
        DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
    )

    # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    print("config_name's type: " )
    print(type(config_name))

    if config_name is None:
        config_name = 'default'

    from .config import config
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    print(app.config)

    #读取配置信息
    from .config import config, ConfigManager
    print(app.config['NACOS_SERVER_ADDRESS'], app.config['NACOS_USERNAME'], app.config['NACOS_PASSWORD'], app.config['NACOS_NAMESPACE'], app.config['NACOS_DATA_ID'])
    client = NacosClient(app.config['NACOS_SERVER_ADDRESS'],
                         namespace=app.config['NACOS_NAMESPACE'],
                         username=app.config['NACOS_USERNAME'],
                         password=app.config['NACOS_PASSWORD'])
    print(client.get_config(app.config['NACOS_DATA_ID'], 'DEFAULT_GROUP'))

    # config_manager = ConfigManager()
    # config_manager.load_from_nacos(client, app.config['NACOS_DATA_ID'], "DEFAULT_GROUP")

    config_manager = ConfigManager(client)
    config_manager.refresh_config(app.config['NACOS_DATA_ID'], "DEFAULT_GROUP")
    config_manager.start_listening(app.config['NACOS_DATA_ID'], "DEFAULT_GROUP")


    print(config_manager.config)
    print(config_manager.config.buk.eotms.wxapp.app_id)
    print(config_manager.config.buk.eotms.wxapp.app_memo)
    print(config_manager.config.buk.eotms.database.url)

    # 配置 MySQL 连接信息（关键配置）
    # 主数据库配置
    app.config['SQLALCHEMY_DATABASE_URI'] = config_manager.config.buk.eotms.database.url
    # 附加数据库配置（通过别名绑定）
    app.config['SQLALCHEMY_BINDS'] = {
        'hotel_db': config_manager.config.buk.hotel.database.url
    }

    # 可选配置
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False  # 关闭警告
    app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {
        'pool_size': 10,  # 连接池大小
        'pool_recycle': 3600,  # 连接回收时间（秒）
        'connect_args': {
            'charset': 'utf8mb4'  # 设置字符集
        }
    }

    # 加载配置
    # app.config.from_object(config_class)

    # 初始化扩展
    initialize_extensions(app)

    # 注册蓝图
    register_blueprints(app)

    # db = SQLAlchemy(app)




    # a simple page that says hello
    @app.route('/hello')
    def hello():
        return 'Hello, World!'


    # from . import db
    # db.init_app(app)

    CORS(app)  # 允许所有来源访问所有路由

    return app


def initialize_extensions(app):
    # 初始化 SQLAlchemy
    db.init_app(app)

    # 可选：在应用上下文中创建表（开发用）
    # with app.app_context():
    #     db.create_all()

def register_blueprints(app):
    from . import auth
    app.register_blueprint(auth.bp)

    from . import blog
    app.register_blueprint(blog.bp)
    app.add_url_rule('/', endpoint='index')

    from . import city
    app.register_blueprint(city.city_bp)
    app.add_url_rule('/', endpoint='index')

    from . import hotel
    app.register_blueprint(hotel.hotel_bp)